<template>
  <div class="notice-container">
    <el-card class="notice-card">
      <template #header>
        <div class="card-header">
          <div>
            <span class="header-title">通知公告管理</span>
            <span class="header-subtitle">管理系统的通知公告，支持多种类型的公告发布</span>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd" v-hasPermi="['system:notice:add']">
              <i class="el-icon-plus"></i> 新增
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="公告标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入公告标题"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="公告类型" clearable>
            <el-option
              v-for="dict in noticeTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="公告状态" clearable>
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            @click="handleBatchDelete"
            :disabled="multiple"
            v-hasPermi="['system:notice:remove']"
          >批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-check"
            @click="handleBatchPublish"
            :disabled="multiple"
            v-hasPermi="['system:notice:publish']"
          >批量发布</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 通知公告表格 -->
      <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="公告标题" align="center" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="公告类型" align="center" prop="type" width="100">
          <template #default="scope">
            <dict-tag :options="noticeTypeOptions" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="statusOptions" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建者" align="center" prop="createBy" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="150" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              v-hasPermi="['system:notice:query']"
            >预览</el-button>
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:notice:edit']"
              v-if="scope.row.status === '1'"
            >修改</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:notice:remove']"
            >删除</el-button>
            <el-button
              v-if="scope.row.status === '1'"
              type="text"
              icon="el-icon-position"
              @click="handlePublish(scope.row)"
              v-hasPermi="['system:notice:publish']"
            >发布</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改通知公告对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="公告标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="dict in noticeTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公告内容" prop="content">
              <el-input
                v-model="form.content"
                type="textarea"
                placeholder="请输入公告内容"
                :rows="8"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公告状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否置顶" prop="isTop">
              <el-radio-group v-model="form.isTop">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.status === '0'">
          <el-col :span="24">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                placeholder="选择发布时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览公告对话框 -->
    <el-dialog title="公告预览" v-model="previewOpen" width="700px" append-to-body>
      <div class="notice-preview">
        <div class="notice-preview-header">
          <h2 class="notice-preview-title">{{ preview.title }}</h2>
          <div class="notice-preview-info">
            <span>发布人: {{ preview.createBy }}</span>
            <span>发布时间: {{ preview.publishTime || preview.createTime }}</span>
            <span>公告类型: 
              <dict-tag :options="noticeTypeOptions" :value="preview.type" />
            </span>
          </div>
        </div>
        <div class="notice-preview-content">
          {{ preview.content }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getNoticeList, getNoticeDetail, addNotice, updateNotice, deleteNotice, publishNotice, cancelNotice } from '@/api/system/notice'

// 是否显示搜索表单
const showSearch = ref(true)

// 总条数
const total = ref(0)

// 通知公告表格数据
const noticeList = ref([])

// 弹出层标题
const title = ref('')

// 是否显示弹出层
const open = ref(false)
const previewOpen = ref(false)

// 日期范围
const dateRange = ref([])

// 是否显示加载动画
const loading = ref(false)

// 选中数组
const ids = ref([])

// 非多个禁用
const multiple = ref(true)

// 预览对象
const preview = reactive({
  noticeId: undefined,
  title: undefined,
  type: undefined,
  content: undefined,
  status: undefined,
  createBy: undefined,
  createTime: undefined,
  publishTime: undefined
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  type: '',
  status: '',
  beginTime: '',
  endTime: ''
})

// 表单参数
const form = reactive({
  noticeId: undefined,
  title: '',
  type: '1',
  content: '',
  status: '0',
  isTop: '0',
  publishTime: undefined
})

// 表单校验
const rules = {
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度必须在2-50个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '内容不能为空', trigger: 'blur' }
  ]
}

// 字典数据
const noticeTypeOptions = ref([
  { value: '1', label: '通知' },
  { value: '2', label: '公告' },
  { value: '3', label: '提醒' }
])

const statusOptions = ref([
  { value: '0', label: '已发布' },
  { value: '1', label: '草稿' }
])

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getNoticeList(queryParams)
    noticeList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取通知公告列表失败', error)
  } finally {
    loading.value = false
  }
}

// 重置查询参数
const resetQuery = () => {
  queryParams.title = ''
  queryParams.type = ''
  queryParams.status = ''
  queryParams.beginTime = ''
  queryParams.endTime = ''
  queryParams.pageNum = 1
  getList()
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 处理分页
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

const handleCurrentChange = (current) => {
  queryParams.pageNum = current
  getList()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.noticeId = undefined
  form.title = ''
  form.type = '1'
  form.content = ''
  form.status = '0'
  form.isTop = '0'
  form.publishTime = undefined
}

// 打开新增弹窗
const handleAdd = () => {
  resetForm()
  open.value = true
  title.value = '新增通知公告'
}

// 打开修改弹窗
const handleUpdate = async (row) => {
  resetForm()
  const noticeId = row.noticeId || row.id
  try {
    const res = await getNoticeDetail(noticeId)
    Object.assign(form, res.data)
    open.value = true
    title.value = '修改通知公告'
  } catch (error) {
    console.error('获取通知公告详情失败', error)
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      const isUpdate = form.noticeId !== undefined
      try {
        if (isUpdate) {
          await updateNotice(form)
          ElMessage.success('修改成功')
        } else {
          await addNotice(form)
          ElMessage.success('新增成功')
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交通知公告失败', error)
      }
    }
  })
}

// 删除操作
const handleDelete = (row) => {
  const noticeId = row.noticeId || row.id
  ElMessageBox.confirm('确认删除该通知公告吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteNotice(noticeId)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除通知公告失败', error)
    }
  }).catch(() => {})
}

// 发布通知公告
const handlePublish = async (row) => {
  const noticeId = row.noticeId || row.id
  try {
    await publishNotice(noticeId)
    ElMessage.success('发布成功')
    getList()
  } catch (error) {
    console.error('发布通知公告失败', error)
  }
}

// 撤销通知公告
const handleCancel = async (row) => {
  const noticeId = row.noticeId || row.id
  try {
    await cancelNotice(noticeId)
    ElMessage.success('撤销成功')
    getList()
  } catch (error) {
    console.error('撤销通知公告失败', error)
  }
}

// 查看通知公告
const handleView = async (row) => {
  const noticeId = row.noticeId || row.id
  try {
    const res = await getNoticeDetail(noticeId)
    const data = res.data
    
    ElMessageBox.alert(
      `<div class="notice-detail">
        <div class="notice-content">${data.content}</div>
        <div class="notice-info">
          <p>发布人：${data.createBy}</p>
          <p>发布时间：${data.publishTime || '未发布'}</p>
          <p>备注：${data.remark || '无'}</p>
        </div>
      </div>`,
      data.title,
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭'
      }
    )
  } catch (error) {
    console.error('获取通知公告详情失败', error)
  }
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.noticeId)
  multiple.value = !selection.length
}

// 批量删除
const handleBatchDelete = () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm(`是否确认删除通知公告编号为${ids.value}的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    getList()
  })
}

// 批量发布
const handleBatchPublish = () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要发布的公告')
    return
  }
  ElMessageBox.confirm(`是否确认发布所选的${ids.value.length}条公告?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    ElMessage.success('批量发布成功')
    getList()
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  resetForm()
}

onMounted(() => {
  // 获取通知公告列表
  getList()
})
</script>

<style scoped>
.notice-container {
  padding: 20px;
}

.notice-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}

.header-subtitle {
  font-size: 13px;
  color: #909399;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: center;
  padding-top: 10px;
}

.notice-preview {
  padding: 10px;
}

.notice-preview-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
  margin-bottom: 15px;
}

.notice-preview-title {
  text-align: center;
  margin-bottom: 15px;
  font-size: 20px;
  font-weight: bold;
}

.notice-preview-info {
  display: flex;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}

.notice-preview-info span {
  margin: 0 10px;
}

.notice-preview-content {
  line-height: 1.8;
  font-size: 14px;
  white-space: pre-wrap;
  word-break: break-all;
}
</style> 